package com.guosen.web.mocker

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * Created by kerry on 2016/10/25.
 * jetty handler simple dispatcher
 */
class Handler {
    private static Handler inst = new Handler()

    private Handler() {}

    public static Handler getInst() {
        return inst
    }

    private Map<String, Caller> routers = new HashMap<String, Caller>()

    public Handler add(String url, Caller caller) {
        routers[url] = caller

        this
    }

    public void route(HttpServletRequest req, HttpServletResponse resp) {
        String url = req.requestURI
        for (one in routers) {
            if (one.key == url) {
                one.value.call(req, resp)
                return
            }
        }

        // default return mock data
        req.setAttribute('url', url)
        Caller c = routers['/xmock']
        c.call(req, resp)
    }
}
